<template>
  <div class="page-login">
    <el-form ref="myForm" class="page-login__form" label-width="80px" :model="model" :rules="rules">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="model.username" />
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input v-model="model.password" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :loading="loading" style="width: 100%" @click="handleLogin">
          登录
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { usePermissionStore } from '@/stores/permission'
import dashboardRoutes from '@/router/modules/dashboard'

const router = useRouter()
const userStore = useUserStore()
const permissionStore = usePermissionStore()

// 请求中
const loading = ref(false)

// 表单数据
const model = reactive({
  username: 'admin',
  password: 'admin'
})

// 表单规则
const rules = {
  username: [{ required: true, message: '用户名必须输入' }],
  password: [{ required: true }]
}

const myForm = ref()
/**
 * 处理登录
 */
async function handleLogin() {
  try {
    // 校验
    await myForm.value.validate()
    // 开启 loading
    loading.value = true
    // 调用 userStore.login 方法
    await userStore.login(model.username, model.password)
    // 登录成功
    ElMessage.success('登录成功')
    // 跳转页面，
    //  使用命名路由来跳转的话，如果该路由没有在路由器中，则直接报错了，url地址不会变化，路由守卫不会进去
    // router.replace({ name: 'dashboard_console' })
    router.replace('/dashboard/console')

    // // 获取用户信息
    // const userInfo = await userStore.getInfo()
    // console.log('userInfo', userInfo)

    // // 构建生成有权限的路由数据
    // const permissionRoutes = await permissionStore.generateRoutes(userInfo)

    // console.log('permissionRoutes', permissionRoutes)
    // // console.log(router.getRoutes())

    // /**
    //  * Vue-Router@4 循环有权限的路由数组，一个一个路由添加，router.addRoute()
    //  * Vue-Router@3 router.addRoutes()
    //  */
    // permissionRoutes.forEach((route) => {
    //   router.addRoute(route)
    // })

    // // 跳转页面
    // router.replace({ name: 'dashboard_console' })
  } catch (error) {
    console.log(error)
    // 关闭 loading，让按钮可以再次点击
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
.page-login {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background-color: #ccc;

  &__form {
    padding: 30px;
    width: 300px;
    border: 1px solid #000;
    background-color: #fff;
  }
}
</style>
